//
//  TSCVCSelectCity.m
//  Tsc_IOS
//
//  Created by Rio on 15-5-24.
//  Copyright (c) 2015年 idream. All rights reserved.
//
// TODO UIImageView展示多张图片后，如何进行内存回收？
// TODO 高德地图定位还没写

#import "TSCVCReg2SelectCity.h"
#import "TSCSDK.h"
#import "TSCVCReg2GatherInfoGuide.h"
#import "TSCVCReg2Welcome.h"

@interface TSCVCReg2SelectCity () {
    // 输入项
    NSInteger _iUserRole;
    
    TSCMySpinner * _spCity;
}

@property (weak, nonatomic) IBOutlet UIImageView *ivCityPhoto;
@property (weak, nonatomic) IBOutlet UIButton *btnConfirm;

@end

@implementation TSCVCReg2SelectCity

#pragma mark 获取并校验输入
- (void) getVCInput:(NSNotificationCenter *)notification {
    [super getVCInput:notification];
    
    _iUserRole = [[_inputDic objectForKey:AEKI_USER_ROLE] intValue];
    
    NSAssert(_iUserRole != 0, @"%s: 输入参数必须包括：%@！", __FUNCTION__, AEKI_USER_ROLE);
}

+ (id) vcReg2SelectCityWithStoryboard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_REG2_SELECT_CITY];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 设置自定义导航栏
    _nbc = [[TSCMyNaviBarCreator alloc]initAndCreateWithViewController:self hasGoBackButton:YES goBackVC:nil hasAppLogo:YES titleResourceKey:@"title_select_city" iconResourceNameArray:nil iconClickedListenerArray:nil];
    
    // 添加spinner
    _spCity = [[TSCMySpinner alloc]init];
    CGFloat spH = 30;
    _spCity.frame = CGRectMake(_btnConfirm.frame.origin.x, _btnConfirm.frame.origin.y - spH - 8, _btnConfirm.frame.size.width, spH);
    [self.view addSubview: _spCity];
    
    // 添加约束
    // spinner
    _spCity.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[_spCity(_btnConfirm)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_spCity, _btnConfirm)]]; // 宽度
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_ivCityPhoto]-10-[_spCity(30)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_spCity, _ivCityPhoto)]]; // top+高度
    [NSLayoutConstraint constraintWithItem:_spCity attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f].active = YES; // x轴居中
    
    // 注册事件——从spinner中选择城市之后，更换城市图片
    __weak typeof (_spCity) _weakSpCity = _spCity;
    __weak typeof (_ivCityPhoto) _weakIvCityPhoto = _ivCityPhoto;
    _spCity.cellCreator = ^(UITableView * tableView, NSIndexPath * indexPath) {
        static NSString *cellReuseId = @"textCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseId];
            cell.backgroundColor = COLOR_MT_SPINNER_CELL_BG;
        }
        NSUInteger row = [indexPath row];
        TSCJsonCity * cityJson = [_weakSpCity.dataArray objectAtIndex:row];
        NSString * text = cityJson.name;
        if ([text isKindOfClass:[NSString class]] == NO) {
            NSLog(@"[W]%s: MySpinner数据源中，存在不是NSString类型的数据！显示时将抛出异常！数据源中的对象：%@", __FUNCTION__, text);
            
            // 设置为错误提示
            text = @"数据源类型不是NSString！";
        }
        
        cell.textLabel.text = text;
        return cell;
    };
    // 注册事件——从spinner中选择城市之后，更换城市图片
    _spCity.itemSelectedListener = ^(TSCMySpinner * sp, UITableViewCell * cell, NSIndexPath * ip) {
        TSCJsonCity * cityJson = [_weakSpCity.dataArray objectAtIndex:ip.row];
        NSString * cityPicUrl = cityJson.picUrl;
        
        _weakIvCityPhoto.image = nil;
        
        [_weakIvCityPhoto sd_setImageWithURL:[NSURL URLWithString:cityPicUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            _weakIvCityPhoto.alpha = 0;
            
            // 动画显示
            [UIView animateWithDuration:CONFIG_ANIMATION_DURATION_S animations:^{
                _weakIvCityPhoto.alpha = 1;
            }];
        }];
    };
    
    // 从APP_DB读取所有城市
    // 注：仅读取状态为启用的
    [_spCity prepareData_P1:^{
        NSArray * appCityArray = [TSCMyDBHelper selectWithSql:[NSString stringWithFormat:@"SELECT id, name, pic_url FROM %@ WHERE status = %li ORDER BY seq ASC;", DB_TABLE_NAME_CITY, DB_CITY_STATUS_IN_USE]];
        
        NSMutableArray * appCityJsonArray = [NSMutableArray array];
        for (NSDictionary * cityDic in appCityArray) {
            TSCJsonCity * cityJson = [[TSCJsonCity alloc]init];
            cityJson.Id = [[cityDic objectForKey:@"id"] intValue];
            cityJson.name = [cityDic objectForKey:@"name"];
            cityJson.picUrl = [cityDic objectForKey:@"pic_url"];
            [appCityJsonArray addObject:cityJson];
        }
        
        [_spCity.dataArray addObjectsFromArray:appCityJsonArray];
    } completionHandler:^{
        [_spCity applyData];
    }];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)gotoGatherInfo:(id)sender {
    
    // 检查用户选择的城市是否正确
    NSIndexPath * selectedIP = [_spCity getSelectedIndexPath];
    if (selectedIP == nil) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_select_city"];
        return;
    }
    
    // 获得选择的城市id
    TSCJsonCity * cityJson = [_spCity.dataArray objectAtIndex:selectedIP.row];
    
    // 如果身份为导购，还需要继续注册
    if (_iUserRole == DB_USER_ROLE_GUIDE) {
        TSCVCReg2GatherInfoGuide * vcReg2GatherInfoGuide = [TSCVCReg2GatherInfoGuide vcReg2GatherInfoGuideWithStoryboard];
        [[self navigationController]pushViewController:vcReg2GatherInfoGuide animated:YES];
        
        // VC间传递参数
        NSMutableDictionary * inputDic = [NSMutableDictionary dictionary];
        [inputDic setObject:[NSNumber numberWithLong:_iUserRole] forKey:AEKI_USER_ROLE];
        [inputDic setObject:[NSNumber numberWithLong:cityJson.Id] forKey:AEKI_CITY_ID];
        [[NSNotificationCenter defaultCenter]addObserver:vcReg2GatherInfoGuide selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_REG2_GATHER_INFO_GUIDE object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_REG2_GATHER_INFO_GUIDE object:inputDic];
        
        // ...
        // 注：后续流程，会再次回到register2_pre()
    }
    // 如果身份为顾客，注册完成
    else {
        // 进入注册逻辑
        [TSCVCReg2Welcome register2_preWithVC:self ud:_ud userRole:_iUserRole cityId:cityJson.Id shopId:0 tel:@""];
    }
    
}

@end
